<template>
  <el-card>
    <el-button type="primary" @click="openAddDialog">新增用户</el-button>
    <el-table :data="userList" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="userId" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteUser(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 用户表单弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getAllUsers, addUser, updateUser, deleteUser } from '@/api/user';

const userList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增用户');
const form = ref({ userId: null, username: '', email: '', phone: '', gender: '' });
let isEdit = false;

const loadUsers = async () => {
  userList.value = await getAllUsers();
};

const openAddDialog = () => {
  isEdit = false;
  dialogTitle.value = '新增用户';
  form.value = { userId: null, username: '', email: '', phone: '', gender: '' };
  dialogVisible.value = true;
};

const openEditDialog = (user) => {
  isEdit = true;
  dialogTitle.value = '编辑用户';
  form.value = { ...user };
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (isEdit) {
    await updateUser(form.value);
  } else {
    await addUser(form.value);
  }
  dialogVisible.value = false;
  loadUsers();
};

const deleteUserById = async (userId) => {
  await deleteUser(userId);
  loadUsers();
};

const handleDeleteUser = async (userId) => {
  await ElMessageBox.confirm('确定删除该用户吗?', '提示', { type: 'warning' });
  await deleteUserById(userId);
};

onMounted(() => {
  loadUsers();
});
</script>
